<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item to="/home/product/spumanage"
        >商品管理</el-breadcrumb-item
      >
      <el-breadcrumb-item>品牌管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <div class="box">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <h3 style="line-height: 32px">
              <i class="el-icon-s-tools"></i> &nbsp; 管理信息
            </h3>
          </div>
        </el-col>
        <el-col :span="16" style="text-align: right">
          <div class="grid-content bg-purple">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="$router.push('/home/product/addbrand')"
              >新增品牌</el-button
            >
          </div>
        </el-col>
      </el-row>
      <div class="divider"></div>
      <el-row :gutter="15" class="whererow">
        <el-col :span="4" style="line-height: 32px">当前共{{total}}个品牌。</el-col>
        <el-col :span="6">
          <el-input
            v-model="search"
            type="text"
            size="small"
            placeholder="请输入品牌名称"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-col>
      </el-row>
    </div>

    <el-empty
      v-if="!tableData || tableData.length == 0"
      :image-size="200"
    ></el-empty>

    <div v-else>
      <div class="noticerow box">
        <i class="el-icon-edit"></i> &nbsp; 已选择了0项
      </div>
      <el-table
        border
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column align="center" type="selection" width="55">
        </el-table-column>
        <el-table-column align="center" label="编号" width="60" type="index">
        </el-table-column>
        <el-table-column align="center" label="品牌名称">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column align="center" label="首字母" width="100">
          <template slot-scope="scope">{{ scope.row.pinyin }}</template>
        </el-table-column>
        <el-table-column align="center" label="排序" width="100">
          <template slot-scope="scope">{{ scope.row.sort }}</template>
        </el-table-column>
        <el-table-column align="center" label="关键词">
          <template slot-scope="scope">{{ scope.row.keywords }}</template>
        </el-table-column>
        <el-table-column align="center" label="是否启用状态" width="130">
          <template slot-scope="scope">
            <p>
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="scope.row.enable"
                active-color="#1aa"
                inactive-color="#aaa"
                @change="changeSwitch(scope.row.id, scope.row.enable)"
              ></el-switch>
            </p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="170">
            <template slot-scope="scope">
              <el-button
              title="配置类别"
              type="warning"
              size="mini"
              icon="el-icon-setting"
              circle
              @click="showBrandCategoryConfigDialog(scope.row.id)"
            ></el-button>
            <el-button
              title="编辑品牌"
              type="warning"
              size="mini"
              icon="el-icon-edit"
              circle
              @click="
                $router.push(`/home/product/updatebrand/${scope.row.id}`)
              "
            ></el-button>
            <el-button
              title="删除品牌"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              circle
              @click="deleteBrand(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="为当前品牌绑定类别"
      :visible.sync="categoryBrandConfigDialogVisiable"
      :modal-append-to-body="false"
      @open="watchCategoryBrandRelationValuesChange = true"
      @close="watchCategoryBrandRelationValuesChange = false">

      <el-cascader-panel
        ref="cascader"
        filterable
        placeholder="试试 搜索关键字"
        :props="props"
        :options="categoryOptions"
        v-model="categoryBrandRelationValues"
      >
      </el-cascader-panel>

    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      categoryBrandConfigDialogVisiable: false, // 表示类别品牌配置弹窗是否可见
      categoryBrandRelationValues: [], // 表示中当前品牌已经建立好关系的类别ID数组
      selectedBrandId: 0,  // 当前选中项的品牌ID
      watchCategoryBrandRelationValuesChange: false, // 若为false，则不监听categoryBrandRelationValues的变化

      currentPage: 1, // 表示当前页码
      pageSize: 5, // 表示每页多少条
      total: 1, // 表示总条目数
      search: "",
      input: "",
      value: "",
      options: [
        {
          value: "enable",
          label: "启用",
        },
        {
          value: "disable",
          label: "禁用",
        },
      ],
      tableData: [],
      
      props: {
        emitPath: false,  // 设置 false，只返回该节点的值
        multiple: true
      },
      categoryOptions: []
    };
  },

  /** 生命周期方法  组件页面挂载完毕后执行 */
  mounted() {
    // 加载品牌列表
    this.loadBrands()
    // 异步递归加载所有类别列表，并且组织为cascader所需要的数据结构
    this.loadAllCategories()
  },

  /** 定义函数 */
  methods: {

    /** 通过parentId异步加载类别列表 返回结果 */
    async loadCategoriesByParentId(parentId){
      let res = await this.categoryApi.queryByParent({ parentId: parentId })
      console.log("加载" + parentId + "当前类别结果：", res);
      if (res.data.state == 200) {
        let nodes = []
        res.data.data.forEach((item) => {
          nodes.push({
            label: item.name,
            value: item.id,
            leaf: item.parent != 1,
          });
        });
        // 遍历nodes
        for (let i=0; i<nodes.length; i++){
          let item = nodes[i]
          if(!item.leaf){
            let subItems = await this.loadCategoriesByParentId(item.value)
            item.children = subItems
          }
        }
        // 返回nodes
        return nodes
      } else {
        this.$alert(res.data.message, "提示");
      }
    },

    /** 异步递归加载所有类别列表，并且组织为cascader所需要的数据结构 */
    loadAllCategories(parentId){
      if (this.$cookie.get("token")===undefined){
        this.$alert("未登录请登录", '提示')
      }else {
      this.loadCategoriesByParentId(0).then(res=>{
        console.log('通过父类别id加载类别树：', res)
        this.categoryOptions = res
      })}
    },

    /** 确认类别品牌的关联配置 */
    submitCategoryBrandConfig(){

    },

    /** 显示品牌与类别的配置弹窗 */
    showBrandCategoryConfigDialog(selectedBrandId){
      this.selectedBrandId = selectedBrandId
      // 加载当前品牌下的类别列表，存入categoryBrandRelationValues
      this.categoryApi.queryByBrandId({brandId:selectedBrandId}).then(res=>{
        console.log('加载选中品牌下的类别列表', res)
        if(res.data.state==200){
          let ids = []
          res.data.data.forEach(item=>{
            ids.push(item.id)
          })
          this.categoryBrandRelationValues = ids
          this.categoryBrandConfigDialogVisiable = true
        }
      })
    },

    /** 通过开关 修改品牌是否启用状态 */
    changeSwitch(id, enable) {
      console.log("修改品牌是否启用状态", `id:${id} enable:${enable}`);
      if(enable){  // 设置启用品牌
        this.brandApi.enable({id}).then(res=>{
          if (res.data.state == 200) {
            this.$message({
              showClose: true,
              message: "更新品牌状态成功，已启用",
              type: "success",
            });
            // 重建缓存
            this.brandApi.rebuildCache()
          } else {
            this.$alert(res.data.message, "提示");
          }
        })
      }else{
        this.brandApi.disable({id}).then(res=>{
          if (res.data.state == 200) {
            this.$message({
              showClose: true,
              message: "更新品牌状态成功，已禁用",
              type: "success",
            })
            // 重建缓存
            this.brandApi.rebuildCache()
          } else {
            this.$alert(res.data.message, "提示");
          }
        })
      }
    },

    /** 加载品牌列表 */
    loadBrands() {
      let page = this.currentPage;
      let pageSize = this.pageSize;
      if (this.$cookie.get("token")===undefined){
        this.$alert("未登录请登录", '提示')
      }else {
      this.brandApi.query({ page, pageSize }).then((res) => {
        console.log(res);
        this.tableData = res.data.data.list;
        this.total = res.data.data.total;
      });}
    },

    /** 删除品牌 */
    deleteBrand(id) {
      this.$confirm("确认删除该品牌?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 选择确认，执行删除业务
        this.brandApi.delete({ id: id }).then((res) => {
          console.log("删除品牌操作：", res);
          if (res.data.state == 200) {
            // 删除成功，重建缓存，重新加载品牌列表
            return this.brandApi.rebuildCache()
          } else {
            this.$alert(res.data.message, "提示");
          }
        }).then((res)=>{
          console.log('重建缓存完成', res)
          // 重建缓存完毕
          if(res.data.state == 200) {
            this.loadBrands();
          }else{
            this.$alert(res.data.message, "提示");
          }
        })
      })
    },

    /** 处理更新页码后的业务 */
    handleCurrentChange(val) {
      console.log(`即将加载选中页: 第${val}页`);
      this.currentPage = val;
      this.loadBrands();
    },
  },

  /** 监听data中数据的变化 */
  watch: {
    categoryBrandRelationValues(newVals, oldVals){
      // 如果变量标识不监听变化，则直接return
      if(!this.watchCategoryBrandRelationValuesChange) return

      // 统计新选中的ID  newVals中有而oldVals中没有
      let addedIds = []
      newVals.forEach(item=>{
        if(oldVals.indexOf(item) == -1){
          addedIds.push(item)
        }
      })
      // 若有新增，则绑定品牌类别关系  
      addedIds.forEach(categoryId => {
        this.brandCategoryRelationsApi.bind({
          brandId : this.selectedBrandId,
          categoryId : categoryId
        }).then(res=>{
          if(res.data.state==200){
            this.$message({
              showClose: true,
              message: "品牌-类别绑定成功",
              type: "success",
            })
            // 重建缓存
            this.brandApi.rebuildCache()
          }else{
            this.$message({
              showClose: true,
              message: "品牌-类别绑定失败",
              type: "error",
            })
          }
        })
      })
      
      // 统计去掉的ID  oldVals中有而newVals中没有
      let deletedIds = []
      oldVals.forEach(item=>{
        if(newVals.indexOf(item) == -1){
          deletedIds.push(item)
        }
      })
      console.log(`addedIds:${addedIds}  deletedIds:${deletedIds}`)

      // 若有删除，则解绑品牌类别关系
      deletedIds.forEach(categoryId => {
        this.brandCategoryRelationsApi.unbind({
          brandId : this.selectedBrandId,
          categoryId : categoryId
        }).then(res=>{
          if(res.data.state==200){
            this.$message({
              showClose: true,
              message: "品牌-类别解除绑定成功",
              type: "success",
            })
            // 重建缓存
            this.brandApi.rebuildCache()
          }else{
            this.$message({
              showClose: true,
              message: "品牌-类别解除绑定失败",
              type: "error",
            })
          }
        })
      })
    }
  }
};
</script>
